import {setStore, getStore} from '@/utils/store'
import {getAllDept} from '@/api/sys/deptApi'

const dictionaryCache = {
    state: {
        idMap: null,
        codeMap:null,
    },
    actions: {
        initDictionaryCache({commit}) {
            return new Promise(resolve => {
                getAllDept().then(res => {
                    let data = res.data.data;
                    let map = {};
                    let codeMap={}
                    for (let i = 0; i < data.length; i++) {
                        let item = data[i]
                        map[item.id] = item;
                        codeMap[item.code]=item
                    }
                    dictionaryCache.state.idMap = map
                    dictionaryCache.state.codeMap = codeMap
                    resolve()
                })
            })
        },
        getDictionaryId: ({commit}, depId) => {
            return new Promise(resolve => {
                let map = dictionaryCache.state.idMap;
                if (!map) {
                    resolve(null)
                    return null
                }
                if (map[depId]) {
                    resolve(map[depId])
                    return
                }
                resolve(null)
            });
        },
        getDictionaryCode: ({commit}, code) => {
            return new Promise(resolve => {
                let map = dictionaryCache.state.codeMap;
                if (!map) {
                    resolve(null)
                    return null
                }
                if (map[code]) {
                    resolve(map[code])
                    return
                }
                resolve(null)
            });
        },
        getDictionaryNameById(obj, id) {
            return new Promise(resolve => {
                dictionaryCache.actions.getDictionaryId(obj, id).then(res => {
                    if (!res) return resolve("");
                    return resolve(res.name);
                })
            })
        },
        getDictionaryNameByCode(obj, code) {
            return new Promise(resolve => {
                dictionaryCache.actions.getDictionaryCode(obj, code).then(res => {
                    if (!res) return resolve("");
                    return resolve(res.name);
                })
            })
        }
    }
}
export default dictionaryCache
